#include "suppliercomponentspage.h"
#include <QTableWidget>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QMessageBox>
#include <QDebug>
#include <QFont> // For title font

SupplierComponentsPage::SupplierComponentsPage(QWidget *parent) 
    : QWidget(parent), 
      currentComponentListHead(nullptr), 
      currentSupplierId(-1) {
    setupUi();
}

SupplierComponentsPage::~SupplierComponentsPage() {
    // 析构函数
}

void SupplierComponentsPage::setupUi() {
    mainLayout = new QVBoxLayout(this);

    titleLabel = new QLabel(this);
    titleLabel->setObjectName("supplierComponentsPageTitleLabel"); // For styling
    titleLabel->setAlignment(Qt::AlignCenter);
    QFont titleFont = titleLabel->font();
    titleFont.setPointSize(16);
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);
    mainLayout->addWidget(titleLabel);

    // 按钮布局（查看详情和返回）
    QHBoxLayout* buttonsLayout = new QHBoxLayout();
    viewDetailButton = new QPushButton("查看选中器件详情", this);
    viewDetailButton->setObjectName("scpViewDetailButton"); // scp for SupplierComponentsPage
    
    backButton = new QPushButton("返回搜索页", this);
    backButton->setObjectName("scpBackButton");
    
    buttonsLayout->addStretch(); 
    buttonsLayout->addWidget(viewDetailButton);
    buttonsLayout->addSpacing(10); 
    buttonsLayout->addWidget(backButton);
    // buttonsLayout->addStretch(); // Removed to align buttons to right, or add another stretch for center
    mainLayout->addLayout(buttonsLayout);

    componentsTable = new QTableWidget(0, 7, this); // ID, Model, Name, Package, Desc, SupplierID, Qty
    QStringList headers = {"ID", "型号", "名称", "封装", "描述", "供应商ID", "库存"};
    componentsTable->setHorizontalHeaderLabels(headers);
    componentsTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    componentsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    componentsTable->setSelectionMode(QAbstractItemView::SingleSelection);
    componentsTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    componentsTable->setObjectName("supplierComponentsPageTable");
    mainLayout->addWidget(componentsTable, 1); // Table takes most space

    setLayout(mainLayout);

    // 连接信号
    connect(backButton, &QPushButton::clicked, this, &SupplierComponentsPage::onInternalBackButtonClicked);
    connect(viewDetailButton, &QPushButton::clicked, this, &SupplierComponentsPage::onViewDetailButtonClicked);
    connect(componentsTable, &QTableWidget::itemDoubleClicked, this, 
            [this](QTableWidgetItem* item){ // Lambda to adapt signal
                if (item) this->onTableItemDoubleClicked(item);
            }
    );
}

void SupplierComponentsPage::loadComponentsForSupplier(int supplierId, const QString& supplierName, ComponentNode* allComponentsHead) {
    currentSupplierId = supplierId;
    currentSupplierName = supplierName;
    currentComponentListHead = allComponentsHead;

    if (titleLabel) {
        titleLabel->setText(QString("供应商: %1 - 器件列表").arg(supplierName));
    }
    populateComponentsTable();
}

void SupplierComponentsPage::populateComponentsTable() {
    if (!componentsTable) {
        qWarning("SupplierComponentsPage::populateComponentsTable - componentsTable is null.");
        return;
    }
    componentsTable->setRowCount(0); // Clear existing rows

    if (!currentComponentListHead || currentSupplierId == -1) {
        qDebug("SupplierComponentsPage::populateComponentsTable - No component list or supplier ID to filter by for supplier %d.", currentSupplierId);
        return;
    }

    int row = 0;
    qDebug() << "Populating table for supplier ID:" << currentSupplierId << ". Total components to check from head:" << (currentComponentListHead ? "Yes" : "No");
    for (ComponentNode* node = currentComponentListHead; node != nullptr; node = node->next) {
        qDebug() << "  Checking component:" << QString::fromUtf8(node->data.model)
                 << " (ID:" << node->data.id
                 << ", SupplierID:" << node->data.supplier_id
                 << ") against target SupplierID:" << currentSupplierId;
        if (node->data.supplier_id == currentSupplierId) {
            qDebug() << "    MATCH FOUND: Adding" << QString::fromUtf8(node->data.model) << "to table.";
            componentsTable->insertRow(row);
            componentsTable->setItem(row, 0, new QTableWidgetItem(QString::number(node->data.id)));
            componentsTable->setItem(row, 1, new QTableWidgetItem(QString::fromUtf8(node->data.model)));
            componentsTable->setItem(row, 2, new QTableWidgetItem(QString::fromUtf8(node->data.name)));
            componentsTable->setItem(row, 3, new QTableWidgetItem(QString::fromUtf8(node->data.package)));
            componentsTable->setItem(row, 4, new QTableWidgetItem(QString::fromUtf8(node->data.description)));
            componentsTable->setItem(row, 5, new QTableWidgetItem(QString::number(node->data.supplier_id)));
            componentsTable->setItem(row, 6, new QTableWidgetItem(QString::number(node->data.quantity)));
            row++;
        }
    }
    qDebug() << "Populated table for supplier ID" << currentSupplierId << "with" << row << "components.";
}

void SupplierComponentsPage::onInternalBackButtonClicked() {
    emit backToSearchRequested();
}

void SupplierComponentsPage::onViewDetailButtonClicked() {
    if (!componentsTable) return;
    int currentRow = componentsTable->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "未选择", "请先在列表中选择要查看详情的元器件。");
        return;
    }
    QTableWidgetItem* idItem = componentsTable->item(currentRow, 0); 
    if (!idItem) {
        qWarning("ID item is null in onViewDetailButtonClicked");
        return;
    }

    bool ok;
    int componentId = idItem->text().toInt(&ok);
    if (ok) {
        emit viewComponentDetailRequested(componentId);
    } else {
        QMessageBox::critical(this, "错误", "无法读取所选元器件的ID。");
    }
}

void SupplierComponentsPage::onTableItemDoubleClicked(QTableWidgetItem* item) {
    if (!item) return;
    QTableWidgetItem* idItem = componentsTable->item(item->row(), 0);
    if (!idItem) {
        qWarning("ID item is null in onTableItemDoubleClicked for row %d", item->row());
        return;
    }

    bool ok;
    int componentId = idItem->text().toInt(&ok);
    if (ok) {
        emit viewComponentDetailRequested(componentId);
    } else {
        QMessageBox::critical(this, "错误", "无法读取双击元器件的ID。");
    }
}